import os
import sys
import time
import subprocess
import webbrowser
from threading import Thread

def install_dependencies():
    """安装所需的依赖项"""
    print("正在检查并安装依赖项...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
        print("依赖项安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"安装依赖项失败: {e}")
        print("请尝试手动安装依赖: pip install -r requirements.txt")
        return False

def run_flask_app():
    """在后台运行Flask应用"""
    print("正在启动Flask应用...")
    env = os.environ.copy()
    env["FLASK_APP"] = "app.py"
    flask_process = subprocess.Popen(
        [sys.executable, "-m", "flask", "run", "--host=0.0.0.0", "--port=5000"], 
        env=env,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True
    )
    
    # 读取并打印Flask的输出
    def print_output():
        for line in flask_process.stdout:
            print(f"Flask: {line.strip()}")
    
    Thread(target=print_output, daemon=True).start()
    
    # 等待Flask启动
    time.sleep(3)
    return flask_process

def check_ngrok():
    """检查ngrok是否已安装"""
    try:
        import pyngrok
        return True
    except ImportError:
        print("未找到pyngrok模块，尝试安装...")
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", "pyngrok"], check=True)
            return True
        except subprocess.CalledProcessError:
            print("安装pyngrok失败，请手动安装: pip install pyngrok")
            return False

def start_ngrok():
    """启动ngrok并获取公网URL"""
    if not check_ngrok():
        print("无法启动ngrok隧道")
        print("您仍然可以通过本地地址访问服务: http://localhost:5000")
        return None
        
    try:
        from pyngrok import ngrok, conf
        
        # 清理现有的ngrok隧道
        for tunnel in ngrok.get_tunnels():
            ngrok.disconnect(tunnel.public_url)
            
        # 启动ngrok HTTP隧道
        print("正在启动ngrok隧道...")
        http_tunnel = ngrok.connect(5000, "http")
        public_url = http_tunnel.public_url
        
        print("\n服务已成功启动!")
        print(f"外网访问地址: {public_url}")
        print(f"API端点: {public_url}/extract?url=你的图片URL")
        print(f"本地访问地址: http://localhost:5000")
        print("\n使用方法:")
        print("1. 在浏览器中访问上述外网地址")
        print("2. 或者直接通过API端点发送请求，例如:")
        print(f"   {public_url}/extract?url=https://example.com/wechat_screenshot.jpg")
        print("\n按Ctrl+C停止服务\n")
        
        # 尝试打开浏览器
        try:
            webbrowser.open(public_url)
        except:
            pass
        
        return public_url
    except Exception as e:
        print(f"启动ngrok时出错: {str(e)}")
        print("您仍然可以通过本地地址访问服务: http://localhost:5000")
        return None

if __name__ == "__main__":
    try:
        # 安装依赖
        if not install_dependencies():
            print("使用已安装的依赖继续运行...")
        
        # 启动Flask应用
        flask_process = run_flask_app()
        
        # 启动ngrok
        public_url = start_ngrok()
        
        # 保持程序运行
        try:
            print("服务正在运行中，按Ctrl+C停止...")
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n正在关闭服务...")
        finally:
            # 终止Flask进程
            flask_process.terminate()
            print("服务已关闭")
    
    except Exception as e:
        print(f"启动服务时出错: {str(e)}")
        sys.exit(1)
